package cn.ytr.crm.web.controller;

import cn.ytr.crm.query.PageResult;
import cn.ytr.crm.query.QueryObject;
import cn.ytr.crm.service.IPermissionService;
import cn.ytr.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/permission")
@Controller
public class PermissionController {

	@Autowired
	IPermissionService permissionService;

	/**
	 * 显示 权限列表页
	 */
	@RequiresPermissions(value = {"访问:权限列表页面", "permission:list"}, logical = Logical.OR)
    //@RequiredPermission(name = "访问权限列表页面", expression = "permission:list")
	@RequestMapping("/list")
	public String list(@ModelAttribute("qo") QueryObject qo, Model model) {
		PageResult result = permissionService.query(qo);
		model.addAttribute("result", result);
		model.addAttribute("qo", qo);
		return "permission/list";
	}

	/**
	 * 显示 无权限页面
	 */
	@RequestMapping("/nopermission")
	public String nopermission(Model model) {
		return "common/nopermission";
	}

	/**
	 * ajax 处理 删除权限
	 */
    @RequiresPermissions(value = {"操作:删除权限", "permission:delete"}, logical = Logical.OR)
    //@RequiredPermission(name = "操作删除权限", expression = "permission:delete")
	@ResponseBody
	@RequestMapping("/delete")
	public JsonResult delete(Long id) {
    	JsonResult jsonResult = new JsonResult();
    	try {
			permissionService.delete(id);
    	    return jsonResult;
    	} catch (Exception e) {
    	    jsonResult.mark("服务器提示：删除权限操作出错");
    	    e.printStackTrace();
    	    return jsonResult;
    	}
	}

	/**
	 * ajax 处理 权限列表页的重新加载按钮的点击，自动更新权限表
	 */
    //@RequiresPermissions(value = {"操作:重新加载权限", "permission:onload"}, logical = Logical.OR)
    //@RequiredPermission(name = "操作重新加载权限", expression = "permission:onload")
	@RequestMapping("/onload")
	@ResponseBody
	public JsonResult onload() {
	    //返回的结果
        JsonResult result = new JsonResult();

        //具体业务处理
        try {
            permissionService.onload();
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("操作失败");
        }

        return result;
	}

	/**
	 * ajax 处理 刷新当前用户权限，更新 session 里的用户权限
	 */
	@RequestMapping("/refreshSelfPermisson")
	@ResponseBody
	public JsonResult refreshSelfPermisson() {
		JsonResult result = new JsonResult();
		try {
			permissionService.refreshSelfPermisson();
		} catch (Exception e) {
			e.printStackTrace();
			result.mark("操作失败");
		}

		return result;
	}
	
}
